package com.finger.gulimall.order.service.impl;

import com.finger.gulimall.order.entity.OrderEntity;
import com.finger.gulimall.order.entity.OrderReturnReasonEntity;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @ClassName RabbitTest
 * @Description TODO
 * @Author finger
 * @Date 2022/7/3 13:19
 * @Version 1.0
 */


@Service
public class RabbitTestService {

    /**
     * 使用Rabbit监听
     * 方式一：
     * 将@RabbitListener（监听队列消息 queues指定监听队列名）标在方法上，该方法就监听着该队列中的消息
     * 方法可以声明哪些参数
     * Message 上游服务器的信息整体，Object 上游服务器传入的对象实体，Channel 信道
     * <p>
     * 方式二：
     * 将@RabbitListener标在类上，然后在方法上标注@RabbitHandler监听队列消息，
     * 调用哪个方法取决于上游服务器发送消息实体类型匹配哪个方法第二个参数
     * <p>
     * 方法参数的第二个参数由rabbit整合会自动解析成我们所需要的对象类型
     */
//    @RabbitListener(queues = "hello.queue")
    //    @RabbitHandler
    // @RabbitListener(queues = "hello.queue")
    public void orderMessage(Message message, OrderEntity obj, Channel channel) {
        // System.out.println("orderMessage:收到消息=》" + message + "；对象实体：" + obj.toString());
        System.out.println("orderMessage:收到消息,对象实体：" + obj.toString());
        // 当前信道中的消息会带有一个序号
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            // 开启消息手动应答
            // deliveryTag当前消息在信道内的序号，multiple当前信道内消息是否批量应答
            channel.basicAck(deliveryTag, false);
            System.out.println("orderMessage：" + deliveryTag);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //    @RabbitHandler
//    @RabbitListener(queues = "hello.queue")
    public void orderReturnMessage(Message message, OrderReturnReasonEntity obj, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            // 拒收当前消息
            // long deliveryTag 当前信道内消息序号, boolean multiple 是否批量应答, boolean requeue 拒收后是否入队列
            channel.basicNack(deliveryTag, false, false);
            System.out.println("orderReturnMessage：" + deliveryTag);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("orderReturnMessage:收到消息,对象实体：" + obj.toString());
    }

    @RabbitListener(queues = "order.release.order.queue")
    public void orderRelease(Message message, String str, Channel channel) throws IOException {
        channel.basicAck( message.getMessageProperties().getDeliveryTag(),false);
        System.out.println(str + "---->" + message.getMessageProperties().getDeliveryTag());
    }

}
